package com.hd.controller;

import com.hd.entity.Result;
import com.hd.entity.User;
import com.hd.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 59899
 */
@RestController
@CrossOrigin
public class LoginController {
    @Autowired
    private LoginService loginService;
    /**
     * 登录
     */
    @RequestMapping("/login")
    public Object login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        User user = loginService.login(username);
        try {
            subject.login(token);
            return new Result(200,"登录成功",user);
        } catch (UnknownAccountException e) {
            return new Result(400,"用户不存在",null);
        } catch (IncorrectCredentialsException e) {
            return new Result(400,"密码错误",null);
        } catch (Exception e) {
            return new Result(400,"其他错误",null);
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result(200,"退出登录",null);
    }


}
